import { Tag, Popover, Button } from 'antd'
import { AvatarImage } from '@/desktop/components'
import { colors, lightBorder, ellipsis } from '@/desktop/styles'
import { useEmotionClassName } from '@/lib/emotion'
import { useStreams } from '@/lib/utils'
import services from '@/services'

export function Observing() {
  const getClassName = useEmotionClassName()

  const [accounts, readonly] = useStreams(
    services.auth.observing.accounts$,
    services.auth.observing.readonly$,
  )

  if (!accounts) return null

  const panel = <>
    <header>被观察账号</header>
    <main>
      {accounts.map(account => <div key={account.id} css={s.account}>
        <AvatarImage size={32} src={account.avatar} />
        <div className="info">
          <div className="name">{account.name}</div>
          {account.remark ? <div className="remark">{account.remark}</div> : null}
        </div>
      </div>)}
    </main>
    <footer>
      <Button type="link" onClick={() => services.auth.observing.switchReadonly()}>
        切换到{readonly ? '读写' : '只读'}
      </Button>
      <Button type="link" danger onClick={() => services.auth.observing.leave()}>
        退出模式
      </Button>
    </footer>
  </>

  return <div css={s.observing}>
    <Popover content={panel} overlayClassName={getClassName(s.panel)}>
      <div className="inner">
        <Tag color="#108ee9">观察者模式</Tag>
        {readonly ? (
          <Tag color="#fff" style={{ color: '#333' }}>
            只读
          </Tag>
        ) : (
          <Tag color="#ff7a45">读写</Tag>
        )}
      </div>
    </Popover>
  </div>
}

const s = {
  observing: css`
    align-items: center;
    display: flex;
    .inner {
      border-radius: 4px;
      box-shadow: 1px 1px 2px #eee;
      cursor: pointer;
      line-height: 0;
      overflow: hidden;
    }
    .ant-tag {
      border-radius: 0;
      margin: 0;
    }
  `,
  panel: css`
    .ant-popover-inner {
      padding: 0;
      width: 300px;
    }
    header {
      padding: 12px;
      color: ${colors.gray};
    }
    main {
      max-height: 260px;
      overflow-y: auto;
      padding-bottom: 12px;
    }
    footer {
      border-top: ${lightBorder};
      display: flex;
      justify-content: space-between;
      padding: 4px 0;
    }
  `,
  account: css`
    align-items: center;
    display: flex;
    font-size: 12px;
    padding: 0 12px;
    line-height: 1.4;
    &:not(:last-child) {
      margin-bottom: 10px;
    }
    .qun-avatar-image {
      margin-right: 8px;
    }
    .info {
      overflow: hidden;
    }
    .name,
    .remark {
      ${ellipsis};
    }
    .remark {
      color: ${colors.gray};
    }
  `,
}
